/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pacificlms.MainPanel;


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.JOptionPane;
import pacificlms.LoggedMember;
import pacificlms.MasterConnection;
import pacificlms.Verifiable.Database.CheckOut;
import pacificlms.Verifiable.Database.Copy;
import pacificlms.Verifiable.Database.Hold;
import pacificlms.Verifiable.Database.Resource;
import pacificlms.Verifiable.Database.CourseReserve;
import pacificlms.Verifiable.Database.Member;
import pacificlms.Verifiable.VerifiableObject;

/**
 *
 * @author Yasir Tanveer
 */
public class ActionHoldResource extends CentralUIPanel {

    /**
     * Creates new form ActionHoldResource
     */
    public ActionHoldResource() {
        super(null);
        initComponents();
        if (!LoggedMember.getInstance().IsLibrarian())
        {
            txtMemberCard.setEnabled(false);
            txtMemberCard.setText(LoggedMember.getInstance().LibraryCardNumber(null));
        }
    }

    @Override
    public String TabName()
    {
        return "Hold";
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel8 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jButton5 = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        txtResourceCode = new javax.swing.JTextField();
        txtMemberCard = new javax.swing.JTextField();
        btnHold = new javax.swing.JButton();

        setPreferredSize(new java.awt.Dimension(615, 535));

        jLabel8.setFont(new java.awt.Font("Tahoma", 0, 22)); // NOI18N
        jLabel8.setText("Hold");

        jLabel6.setText("For Member");

        jButton5.setText("Close");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jLabel9.setText("ResourceCode");

        btnHold.setText("Hold");
        btnHold.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnHoldActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(10, 10, 10)
                        .addComponent(txtResourceCode, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(30, 30, 30)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtMemberCard, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnHold, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(270, 270, 270))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtResourceCode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtMemberCard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnHold)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 378, Short.MAX_VALUE)
                .addComponent(jButton5)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed

        Close();
        
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton5ActionPerformed

    int NumOfAvailableCopy()
    {
        try
        {
            Connection con = MasterConnection.getInstance();
            Statement stmt = con.createStatement();
            String ResourceCode = txtResourceCode.getText();
            int CopyCount, CheckOutCount, HoldCount;
            String SQL = "SELECT Count(*) AS CopyCount FROM copy C WHERE C.resourcecode = '"+ResourceCode+"' AND C.CopyStatus = 'available'";
            String SQL1 = "SELECT Count(*) AS CheckOutCount FROM CheckOut CO WHERE CO.resourcecode ='"+ ResourceCode+ "' AND CO.Finished = '0'";
            String SQL2 = "SELECT Count(*) AS HoldCount FROM hold H  WHERE  H.resourcecode ='"+ ResourceCode+ "' AND H.Finished = '0'";
            
            ResultSet RS = stmt.executeQuery(SQL);
            RS.next();
            CopyCount = RS.getInt("CopyCount");
            
            RS = stmt.executeQuery(SQL1);
            RS.next();
            CheckOutCount = RS.getInt("CheckOutCount");
            
            RS = stmt.executeQuery(SQL2);
            RS.next();
            HoldCount = RS.getInt("HoldCount");
            
            return CopyCount-CheckOutCount-HoldCount;
        }
        catch(Exception Ex)
        { 
            JOptionPane.showMessageDialog(null, "Database error, please try again later\n" + Ex.getMessage(), "Database Error", JOptionPane.ERROR_MESSAGE);
            return 999;
        }  
        
    }
    void Hold()
    {
        
        try
        {
            Connection con = MasterConnection.getInstance();
            Statement stmt = con.createStatement();
            GregorianCalendar now= new GregorianCalendar();
            SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
            ResultSet rs;
            String SQL;
            String LibCard = txtMemberCard.getText();
            String ResourceCode = txtResourceCode.getText();
            Hold Hld=new Hold();
            Member Mem = new Member();
            int NumOfAvailableCount;
            Resource Resource=new Resource();
            if(ResourceCode.isEmpty())
            {
                JOptionPane.showMessageDialog(null, "The ResourceCode can not be empty.", "Validation Warning", JOptionPane.WARNING_MESSAGE);
                return;
            }
            Resource.ResourceCode(ResourceCode);
            String ResourceFindSQL = Resource.FindIdenticalSQL();
            ResultSet Rrs = stmt.executeQuery(ResourceFindSQL);
            if(!Rrs.next())
            {
                JOptionPane.showMessageDialog(null, "Unable to find Resource "+ResourceCode+".", "Validation Warning", JOptionPane.WARNING_MESSAGE);
                return;
            }   
            if(LibCard.isEmpty())
            {
                Mem = LoggedMember.getInstance();
            }
            else
            {
                Mem.LibraryCardNumber(LibCard);
                String MemberFindSQL = Mem.FindIdenticalSQL();
                ResultSet Mrs = stmt.executeQuery(MemberFindSQL);
                if(Mrs.next())
                {
                     Mem.FillFromResultSet(Mrs, Mrs.getMetaData());
                }
                   
                else
                {
                    JOptionPane.showMessageDialog(null, "Unable to find member "+LibCard+".", "Validation Warning", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                
            }
            NumOfAvailableCount = NumOfAvailableCopy();

            if(NumOfAvailableCount>0)
            {
                JOptionPane.showMessageDialog(null, "The Resource has available copies, don't need put on hold.", "Validation Warning", JOptionPane.WARNING_MESSAGE);
                return;
            }
            CourseReserve Reserve = new CourseReserve();
            Reserve.ResourceCode(ResourceCode);
            if(Reserve.IsReserved())
            {
                JOptionPane.showMessageDialog(null, "The Resource has been reserved, don't need put on hold.", "Validation Warning", JOptionPane.WARNING_MESSAGE);
                return;
            }
            
            Hld.ResourceCode(ResourceCode);
            Hld.IdentityNumber(Mem.IdentityNumber(null));
            Hld.Finished("0");
            
            String CheckHoldSQL = Hld.FindIdenticalSQL();
            rs = stmt.executeQuery(CheckHoldSQL);
            if (rs.next())
            {
                JOptionPane.showMessageDialog(null, "You already have a hold on this resource.", "Validation Warning", JOptionPane.WARNING_MESSAGE);
                return;
            }
            
            Hld.RequestDate(sf.format(now.getTime()));
            Hld.Verify();
            stmt.executeUpdate(Hld.InsertRecrodSQL());
            String s="Resource is placed on hold successfully and updated in DB";
            JOptionPane.showMessageDialog(this,s);
        }
        catch(Exception Ex)
        { 
            JOptionPane.showMessageDialog(null, "Database error, please try again later\n" + Ex.getMessage(), "Database Error", JOptionPane.ERROR_MESSAGE);
        }// TODO add your handling code here:
    }                     
    
    private void btnHoldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHoldActionPerformed
        Hold();
    }//GEN-LAST:event_btnHoldActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnHold;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JTextField txtMemberCard;
    private javax.swing.JTextField txtResourceCode;
    // End of variables declaration//GEN-END:variables
}
